#!/usr/bin/env python

# *************************************************************************

# Copyright 2010 Texas A&M University, 
#                College Station, Texas
#                Contact: R Crosby (rwc@cs.tamu.edu)
#
# Copyright 2003, 2004 by BiRC -- Bioinformatics Research Center
#                University of Aarhus, Denmark
#                Contact: Thomas Mailund <mailund@birc.dk>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# *************************************************************************

import os
import re
import sys

# *************************************************************************

def CheckSysoutFile(fn):
    """Check the status of a sysout file"""

    modere = re.compile('Parallel Mode.*\{(\d+),(\d+),(\d+)\}')
    filere = re.compile('Binary File \{(.*)\}')
    termre = re.compile('Ended successfully')

    try:
        with open(fn) as sf:
            for ln in sf:
                
                mm = modere.match(ln)
                if mm:
                    xs = mm.group(1)
                    ys = mm.group(2)
                    trees = mm.group(3)

                fm = filere.match(ln)
                if fm:
                    binfile = fm.group(1)

                tm = termre.match(ln)
                if tm:
                    break

            else:
                print >> sys.stderr, "Error in file {0}, did not terminate successfully".format(fn)
                return 0
                
            
    except OSError, err:
        print >> sys.stderr, "Error in file {0}, errno".format(fn), err.errno, err.strerror
        return 0

    return { 'filename' : fn,
             'xs' : xs,
             'ys' : ys,
             'trees' : trees,
             'binfilename' : binfile }

# *************************************************************************

def CheckCompletionStatus(opt):
    """Check all the processing jobs to see if they worked"""

    jn = re.search("(\d+)", opt['jobid'])

    if not jn:
        print >> sys.stderr, "Unable to parse jobno {0}".format(opt['jobid'])
        sys.exit(2)
    
    jobno = jn.group(1)

    rc = 0;
    i = 0;
    files = [0] * opt['jobcount']

    fnre = re.compile('{0}\.{1}.*\.stdout-(\d+)'.format(opt['jobname'], jobno))

    for fn in os.listdir('.'):

        fnme = fnre.match(fn)
        if not fnme:
            continue

        fileno = int(fnme.group(1))
        if fileno >= len(files):
            print >> sys.stderr, "Error, Found excess sydout file {0}".format(fn)
            rc = 3
            break

        if opt['verbose']:
            print >> sys.stderr, 'Checking file {0}:'.format(fn),

        info = CheckSysoutFile(fn)
        if info:
            if opt['verbose']:
                print >> sys.stderr, ' OK'
            files[int(fnme.group(1))] = info
        else:
            if opt['verbose']:
                print >> sys.stderr, ' Not OK'
            else:
                print >> sys.stderr, 'File {0}: Not OK'
                rc = 1
        i += 1

    if i != opt['jobcount']:
        print >> sys.stderr, 'Error: Only found {0} stdout files, should have {1}'.format(i, opt['jobcount'])
        rc = 2

    return rc, files

# *************************************************************************

if __name__ == "__main__":
    print 'Needs to be run from pqqback main'
